﻿using System.Text;

namespace CommonFramework.Log
{
    /// <summary>
    /// 可以对LogMessage的内容进行修改
    /// </summary>
    public class LogMessageModifier
    {
        public LogSeverity Severity;
        private StringBuilder _headBuilder = null;
        private StringBuilder _contentBuilder = null;

        internal LogMessageModifier(LogMessageData msgData)
        {
            this.Indent = 0;
            Severity = msgData.Severity;

            if (!string.IsNullOrEmpty(msgData.RawContent))
                _contentBuilder = new StringBuilder(msgData.RawContent);
        }

        public (string head, string content) GetMessage()
        {
            string head = _headBuilder != null ? _headBuilder.ToString() : "";
            string content = _contentBuilder != null ? _contentBuilder.ToString() : "";
            return (head, content);
        }
        public void AppendHead(string val)
        {
            if (_headBuilder == null)
                _headBuilder = new StringBuilder(val);
            else
                _headBuilder.Append(val);
        }

        #region 消息中每行的头部缩进

        public int Indent { get; private set; }
        public void AddIndent(int addCount = 1)
        {
            Indent += addCount;
        }
        public void RemoveIndent(int removeCount = 1)
        {
            Indent -= removeCount;
            if (Indent < 0)
                Indent = 0;
        }

        #endregion

        #region 消息中附加内容

        public void AppendContent(string val)
        {
            if (Indent > 0 && (_contentBuilder.Length == 0 || val.Contains("\n")))
            {
                bool newline = true;
                for (int i = 0; i < val.Length; ++i)
                {
                    if (newline)
                    {
                        _contentBuilder.Append('\t', Indent);
                        newline = false;
                    }

                    if (val[i] == '\n')
                    {
                        _contentBuilder.AppendLine();
                        newline = true;
                    }
                    else
                    {
                        _contentBuilder.Append(val[i]);
                    }
                }
            }
            else
            {
                _contentBuilder.Append(val);
            }
        }
        public void AppendContentFormat(string val, params object[] args)
        {
            this.AppendContent(string.Format(val, args));
        }
        public void AppendContentLine(string val)
        {
            this.AppendContent(val + "\n");
        }

        #endregion
    }
}